package com.tiny.thread.synchronize.unsynch;

/**
 * Created by zhumenglong on 2017/3/12.
 */
public class TransferRunnable implements Runnable {

    private Bank bank;
    private int fromAccount;
    private double maxAmount;
    private int DELAY = 10;

    /**
     * 构造函数
     *
     * @param b    转账的银行
     * @param from 来源账户
     * @param max  每次转账的最大金额
     */
    public TransferRunnable(Bank b, int from, double max) {
        bank = b;
        fromAccount = from;
        maxAmount = max;
    }

    /**
     * 随机选择一个目标账户和一个随机账户调用bank对象的transfer方法然后睡眠。
     */
    @Override
    public void run() {
        try {
            while (true) {
                int toAccount = (int) (bank.size() * Math.random());
                double amount = maxAmount * Math.random();
                bank.transfer(fromAccount, toAccount, amount);
                Thread.sleep((int) (DELAY * Math.random()));
            }
        } catch (InterruptedException e) {
        }
    }
}
